package common

import (
	"github.com/bwmarrin/snowflake"
	"sync"
)

var Snowflake = snowflakeObject{
	nodeMap: make(map[int64]*snowflake.Node),
}

type snowflakeObject struct {
	nodeMap map[int64]*snowflake.Node
	nodeId  int64
	rwLock  sync.RWMutex
}

var (
// nodeData  nodeInfo
// defaultId int64 //0<=nodeId<=1023
)

func (sf *snowflakeObject) getNode(nodeId int64) (*snowflake.Node, error) {

	sf.rwLock.RLock()
	node := sf.nodeMap[nodeId]
	sf.rwLock.RUnlock()
	if node != nil {
		return node, nil
	}

	var err error
	sf.rwLock.Lock()
	node, err = snowflake.NewNode(nodeId)
	sf.nodeMap[nodeId] = node
	sf.rwLock.Unlock()
	return node, err
}

func (sf *snowflakeObject) GetSnowflakeId(nodeId ...int64) (int64, error) {
	nodeIdValue := sf.nodeId
	if len(nodeId) > 0 {
		nodeIdValue = nodeId[0]
	}
	node, err := sf.getNode(nodeIdValue)
	if err != nil {
		return 0, err
	}

	return node.Generate().Int64(), nil
}

func (sf *snowflakeObject) SetNodeId(nodeId int64) {
	sf.nodeId = nodeId % 1024
}
